package com.shiguiwu.springmybatis.javabase.nio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @description: selector
 * @author: stone
 * @date: Created by 2021/11/9 10:46
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.nio.selector
 */
public class SelectorServerTests {

    public static void main(String[] args) throws Exception {

        //1创建一个socket通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //2设置非阻塞
        serverSocketChannel.configureBlocking(false);

        //3创建一个buffer
        ByteBuffer serverByteBuffer = ByteBuffer.allocate(1024);

        //4绑定InetSocketAddress
        serverSocketChannel.bind(new InetSocketAddress(8888));

        //5创建一个selector
        Selector selector = Selector.open();

        //6注册到selector中,进行监听
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //7选择器进行轮询，进行后续操作
        while (selector.select() > 0) {
            //获取所有的key
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (Iterator<SelectionKey> it = selectionKeys.iterator(); it.hasNext(); ) {
                //获取就绪操作
                SelectionKey key = it.next();
                //判断是什么操作
                if (key.isAcceptable()) {
                    //获取连接
                    SocketChannel accept = serverSocketChannel.accept();
                    //设置非阻塞方式
                    accept.configureBlocking(false);

                    //注册
                    accept.register(selector, SelectionKey.OP_READ);
                }

                else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    //建立一个buffer
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    //读数据
                    int read = 0;
                    while ((read = channel.read(buffer)) > 0) {
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, read));
                        //清缓存
                        buffer.clear();
                    }

                }
                //移除
                it.remove();
            }
        }
    }
}
